import ctypes
import os
import random
import time
from lxml import etree
import wmi
import hashlib
import requests


def get_ua():
    user_agents = [
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',
        'Opera/8.0 (Windows NT 5.1; U; en)',
        'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
        'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
        'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
        'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0) ',
    ]
    user_agent = random.choice(user_agents)  # random.choice(),从列表中随机抽取一个对象
    return user_agent

def get_card_id():
    """
    获取本机主板 ID
    :return: 本机主板序列号
    """
    card_info = wmi.WMI()
    card_id = card_info.Win32_BaseBoard()[0].SerialNumber.strip()
    return card_id

def make_machine_code(card_id):
    """
    将主板序列号处理为机器码
    :return: 机器码
    """
    # MD5加密
    m = hashlib.md5(card_id.encode('utf-8'))
    md5_str = m.hexdigest()
    # 截取前12位
    machine_code = md5_str[0:12]
    return machine_code

def check_authority(machine_code):
    """
    检测机器码是否注册
    :return: 机器码注册结果，True：已注册，False：没注册
    """
    # 向数据库发起请求 获取到所有已经注册的机器码数据
    ua = get_ua()
    codes_url = "https://blog.csdn.net/weixin_41822224/article/details/86088378"  # csdn
    headers = {
        "User-Agent": ua
    }
    try:
        codes_data = requests.get(codes_url, headers=headers)
    except:
        print("异常，无法完成校验，请检查网络后重试")

        code_check = 3
        return code_check
    time.sleep(1)
    codes_str = codes_data.text
    # 检测该机器码是否存在
    if machine_code in codes_str:
        # 存在， 放行 返回结果
        code_check = 1
    else:
        # 不存在，提示内容
        code_check = 2
    return code_check

def administrators_info():
    ua = get_ua()
    codes_url = "http://30606360.blog.hexun.com/117822953_d.html"
    headers = {
        "User-Agent": ua
    }
    reponse_data = requests.get(codes_url, headers=headers)
    time.sleep(1)
    reponse_str = reponse_data.text
    html = etree.HTML(reponse_str)
    administrators_info_str = html.xpath('//div[@id="BlogArticleDetail"]')[0].text
    administrators_info_ = administrators_info_str.replace("\r\n", "").replace(" ", "")
    return administrators_info_

def tips(machine_code_):
    """
    根据检测机器码后的结果，展示对应
    :return:
    """
    # 1、展示用户的注册码 2、展示联系人信息
    desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')
    file_name = desktop_path + "/机器码.txt"
    with open(file_name,"w") as f:
        f.write(machine_code_)
    _info = administrators_info()
    ctypes.windll.user32.MessageBoxA(0, u"该软件暂时还没注册\n您的机器码 (已经保存到桌面: 机器码.txt)，\n{}".format(_info).encode('gb2312'),
                                     u' 提示 ^_^'.encode('gb2312'), 0)

def RegisterCheck(fuc):
    # 获取本机主板 ID
    card_id = get_card_id()
    # 制作成机器码
    machine_code = make_machine_code(card_id)
    # 检测机器码是否注册
    code_check = check_authority(machine_code)
    def inner(*args,**kwargs):
        if code_check == 1:
            # 已注册，放行
            fuc(*args,**kwargs)
        elif code_check == 3: # 异常
            ctypes.windll.user32.MessageBoxA(0, u"或许是网络原因导致验证失败，请检查后重试".encode("gbk"),
                                             u'异常'.encode("gbk"), 0)
        else:
            # 未注册，提示用户注册
            # 根据机器码提示信息
            tips(machine_code)
    return inner


if __name__ == '__main__':
    @RegisterCheck
    def example():
        print("通过")

    example()